//
//  InvestViewController.m
//  WBBaseProject
//
//  Created by 吴斌 on 2018/3/5.
//  Copyright © 2018年 吴斌. All rights reserved.
//

#import "InvestViewController.h"
#import "InvestTableViewCell.h"
#import <ZYSideSlipFilterController.h>
#import <ZYSideSlipFilterRegionModel.h>
#import "CommonItemModel.h"
#import "SideSlipCommonTableViewCell.h"
#import <UIImageView+WebCache.h>
#import "MMComBoBox.h"
#import "InvestNoDataCell.h"
#import "RankAndFiltrateView.h"
#import "BidViewController.h"
#import <MJRefresh.h>
#import "PriceRangeModel.h"

#define kRankViewHeight 45.0f

static NSString * const InvestTableViewCellReuseId = @"InvestTableViewCell";
static NSString * const InvestNoDataCellReuseId = @"InvestNoDataCell";

@interface InvestViewController ()<UITableViewDelegate,UITableViewDataSource,MMComBoBoxViewDataSource, MMComBoBoxViewDelegate,RankAndFiltrateViewDelegate>

@property (nonatomic, strong) NSArray *mutableArray;
//@property (nonatomic, strong) MMComBoBoxView *comBoBoxView;

@property (nonatomic, strong) UITableView *tableView;

@property (strong, nonatomic) ZYSideSlipFilterController *filterController;

@property (strong ,nonatomic) RankAndFiltrateView *rankView;

/** 消息数据 */
@property (nonatomic,strong) NSMutableArray *dataArr;

/** 页数 */
@property (nonatomic,assign) NSInteger page;

@end

@implementation InvestViewController

#pragma mark 滑动隐藏导航栏
//滑动隐藏导航栏 LiXingLe  方案一
-(void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{

    if (velocity.y > 0) {
        self.rankView.mm_top = 20;
        self.tableView.mm_top = 20 + kRankViewHeight;
        self.tableView.mm_height = kScreenHeight - kTabbarHeight - kRankViewHeight - 20;
    }else{
        self.rankView.mm_top = 0;
        self.tableView.mm_top = kRankViewHeight;
        self.tableView.mm_height = kScreenHeight - kNavigationBarHeight - kTabbarHeight - kRankViewHeight;
    }
    
    [WB_SharedApplication setStatusBarStyle:velocity.y<0];
    [self.navigationController setNavigationBarHidden:velocity.y>0 animated:YES];
}

//方案二
//-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
//    CGFloat offsetY = scrollView.contentOffset.y + _tableView.contentInset.top;
//    CGFloat panTranslationY = [scrollView.panGestureRecognizer translationInView:self.tableView].y;
//    DebugLog(@"%f----%f",panTranslationY,offsetY);
//    if (offsetY > 64) {
//        if (panTranslationY > 0) {
//            //下滑趋势，显示
//            [self.navigationController setNavigationBarHidden:NO animated:YES];
//        }else{
//            //上滑趋势，隐藏
//            [self.navigationController setNavigationBarHidden:YES animated:YES];
//        }
//    }else{
//        [self.navigationController setNavigationBarHidden:NO animated:YES];
//    }
//}

#pragma mark - 生命周期 Life Circle
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"散标";
    [self.view addSubview:self.tableView];
    
    [self registerCell];

    //创建复选框
    [self confirFilterController];
    
    self.wb_leftButton.hidden = YES;
    
    //创建排序筛选视图
    [self setUpRankView];

    _page = 1;

    [self addRightButton];
    //刷新数据
    [self refreshDataWithRate:@"" risks:@"" periods:@"" level:@"" sortField:@"" sortType:@""];
    
    [self getFilterData];
}
- (void)getFilterData
{
    [XYHttpRequest dataRequestWithGetInvestRisksuccess:^(id responseObj) {
        
        if (Success) {
            NSMutableArray *a = [NSMutableArray array];
            
            [XYHttpRequest dataRequestWithGetGetInvestLevelsuccess:^(id responseObj) {
                
                if (Success) {
                    NSMutableArray *data = [NSMutableArray array];
                    
                    NSMutableArray *b = [NSMutableArray array];
                    
                    [data addObject:a];
                    [data addObject:b];
                    
                    _filterController.dataList = data;
                }
                
            } failure:^(NSError *error) {
                
            }];
        }
        
    } failure:^(NSError *error) {
        
    }];
}
- (void)refreshDataWithRate:(NSString *)rate risks:(NSString *)risks periods:(NSString *)periods level:(NSString *)level sortField:(NSString *)sortField sortType:(NSString *)sortType{
    WB_WeakSelf(self)

    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakself.dataArr removeAllObjects];
        [weakself loadMoreDataWithPage:_page rate:rate risks:risks periods:periods level:level sortField:sortField sortType:sortType];
        [weakself.tableView.mj_footer resetNoMoreData];
    }];
    self.tableView.mj_header = header;
    
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _page = _page + 1;
        [weakself loadMoreDataWithPage:_page rate:rate risks:risks periods:periods level:level sortField:sortField sortType:sortType];
    }];
    self.tableView.mj_footer = footer;
    
    //马上进入刷新状态
    [self.tableView.mj_header beginRefreshing];
}

- (void)loadMoreDataWithPage:(NSInteger)page rate:(NSString *)rate risks:(NSString *)risks periods:(NSString *)periods level:(NSString *)level sortField:(NSString *)sortField sortType:(NSString *)sortType
{
    
    WB_WeakSelf(self)
    [XYHttpRequest dataRequestInvestWithiInvestRate:rate risks:risks periods:periods level:level sortField:sortField sortType:sortType page:[NSString stringWithFormat:@"%ld",page] rows:@"10" success:^(id responseObj) {
        [weakself.tableView.mj_header endRefreshing];
        [weakself.tableView.mj_footer endRefreshing];
        
        if (Success) {
//            if ([responseObj[@"data"][@"resultMap"] count] == 0) {
//                [weakself.tableView.mj_footer endRefreshingWithNoMoreData];
//            }else{
//                [weakself.dataArr addObjectsFromArray:responseObj[@"data"][@"resultMap"]];
//                WB_DISPATCH_MAIN_THREAD(^{
//                    [weakself.tableView reloadData];
//                })
//            } 
        }
    } failure:^(NSError *error) {
        [NSObject wb_showAlertWithTitle:@"网络异常"];
        [weakself.tableView.mj_header endRefreshing];
        [weakself.tableView.mj_footer endRefreshing]; 
    }];
}


- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
//    [self.comBoBoxView dimissPopView];
    self.navigationController.navigationBarHidden = NO;
    [WB_SharedApplication setStatusBarStyle:UIStatusBarStyleLightContent];
} 

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.rankView.mm_top = 0;
    self.tableView.mm_top = kRankViewHeight;
    self.tableView.mm_height = kScreenHeight - kNavigationBarHeight - kTabbarHeight - kRankViewHeight;
    //防止滑动时导航栏有黑色
    if ([self respondsToSelector:@selector(edgesForExtendedLayout)])
        self.edgesForExtendedLayout = UIRectEdgeNone;
    
    //    [WB_SharedApplication setStatusBarStyle:UIStatusBarStyleLightContent];
}


- (void)addRightButton
{
    UIButton *btn = [UIButton ba_buttonWithFrame:CGRectMake(0, 0, 80, 64) title:@"规则" titleColor:[UIColor whiteColor] titleFont:[UIFont systemFontOfSize:13]];
    [btn ba_button_setButtonLayoutType:BAKit_ButtonLayoutTypeRightImageLeft padding:2.0f];
    btn.titleLabel.textAlignment = NSTextAlignmentRight;
    btn.frame = CGRectMake(0, 0, 80, 64);
    //把视图的边角变为圆形, cornerRadius圆角半径
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    //弹簧控件, 修复边距
    UIBarButtonItem *spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    spaceItem.width = -5;
    self.navigationItem.rightBarButtonItems = @[spaceItem,backItem];
    [btn addTarget:self action:@selector(clickRule:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)clickRule:(UIButton *)sender
{
    
}

#pragma mark - RankAndFiltrateView Delegate
- (void)clickRankView:(RankAndFiltrateView *)view button:(UIButton *)button
{
    [self.tableView.mj_header endRefreshing];
    
    if (button.tag == 1004) {
        
        
        self.tabBarController.tabBar.hidden = YES;
        [_filterController show];
        _tableView.mm_height = kScreenHeight - kNavigationBarHeight - kRankViewHeight;
    }else{
        [self refreshDataWithRate:@"" risks:@"" periods:@"" level:@"" sortField:view.sortField sortType:view.sortType];
        NSLog(@"%@---%@",view.sortField,view.sortType);
    }
}

- (void)setUpRankView
{
//    self.comBoBoxView = [[MMComBoBoxView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 40)];
//    self.comBoBoxView.dataSource = self;
//    self.comBoBoxView.delegate = self;
//    [self.view addSubview:self.comBoBoxView];
//    [self.comBoBoxView reload];
    
    self.rankView = [[RankAndFiltrateView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kRankViewHeight)];
    self.rankView.delegate = self;
    [self.view addSubview:self.rankView];
    
}

//创建复选框
- (void)confirFilterController
{
    self.filterController = [[ZYSideSlipFilterController alloc] initWithSponsor:self resetBlock:^(NSArray *dataList) {
        for (ZYSideSlipFilterRegionModel *model in dataList) {
            //
            for (CommonItemModel *itemModel in model.itemList) {
                [itemModel setSelected:NO];
            }
            model.selectedItemList = nil;
        }
    } commitBlock:^(NSArray *dataList) {
        //Common Region
#pragma mark commit
        
        //价格区间
        ZYSideSlipFilterRegionModel *priceRegionModel = dataList[2];
        PriceRangeModel *priceRangeModel = [priceRegionModel.customDict objectForKey:PRICE_RANGE_MODEL];
        NSMutableString *priceRangeString = [NSMutableString stringWithString:@"\n价格区间: "];
        if (priceRangeModel) {
            [priceRangeString appendFormat:@"%@ - %@", priceRangeModel.minPrice, priceRangeModel.maxPrice];
            if (priceRangeModel.maxPrice.integerValue<priceRangeModel.minPrice.integerValue) {
                
                [NSString wb_showAlertWithTitle:@"价格区间有误！"];
                return ;
            }
        }
        NSLog(@"%@", priceRangeString);
        
        //Common Region
        NSMutableString *commonRegionString = [NSMutableString string];
        for (int i = 0; i < dataList.count; i ++) {
            ZYSideSlipFilterRegionModel *commonRegionModel = dataList[i];
            [commonRegionString appendFormat:@"\n%@:", commonRegionModel.regionTitle];
            NSMutableArray *commonItemSelectedArray = [NSMutableArray array];
            for (CommonItemModel *itemModel in commonRegionModel.itemList) {
                if (itemModel.selected) {
                    [commonItemSelectedArray addObject:[NSString stringWithFormat:@"%@-%@", itemModel.itemId, itemModel.itemName]];
                }
            }
            [commonRegionString appendString:[commonItemSelectedArray componentsJoinedByString:@", "]];
        }
        NSLog(@"哈哈---%@", commonRegionString);
        [self refreshDataWithRate:@"" risks:@"" periods:@"" level:@"" sortField:@"" sortType:@""];
        
        
        _tableView.mm_height = kScreenHeight - kNavigationBarHeight - kRankViewHeight - kTabbarHeight;
        [_filterController dismiss]; 
    }];
    _filterController.animationDuration = .3f;
    _filterController.sideSlipLeading = 0.15 * kScreenWidth;
    _filterController.dataList = [self packageDataList];
    
}

#pragma mark - 模拟数据源
- (NSArray *)packageDataList{
    NSMutableArray *dataArray = [NSMutableArray array];
    [dataArray addObject:[self commonFilterRegionModelWithKeyword:@"风险等级" selectionType:BrandTableViewCellSelectionTypeSingle]];
    [dataArray addObject:[self commonFilterRegionRiswLevelModelWithKeyword:@"智能分级" selectionType:BrandTableViewCellSelectionTypeMultiple]];
    [dataArray addObject:[self commonFilterRegionInterestRateModelWithKeyword:@"利率" selectionType:BrandTableViewCellSelectionTypeMultiple]];
    [dataArray addObject:[self commonFilterRegionTimeLimitModelWithKeyword:@"期限" selectionType:BrandTableViewCellSelectionTypeMultiple]];
    return dataArray;
}


- (void)registerCell
{
    [self.tableView registerNib:[UINib nibWithNibName:InvestTableViewCellReuseId bundle:nil] forCellReuseIdentifier:InvestTableViewCellReuseId];
    [self.tableView registerNib:[UINib nibWithNibName:InvestNoDataCellReuseId bundle:nil] forCellReuseIdentifier:InvestNoDataCellReuseId];
}

#pragma mark - 懒加载  Lazy Load
- (UITableView *)tableView
{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kRankViewHeight, kScreenWidth, kScreenHeight - kNavigationBarHeight - kTabbarHeight - kRankViewHeight) style:UITableViewStylePlain];
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableFooterView = [UIView new];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    return self.dataArr.count ? self.dataArr.count : 1;
}

- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath { 
    if (self.dataArr.count) {
        InvestTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:InvestTableViewCellReuseId forIndexPath:indexPath];
        cell.data = _dataArr[indexPath.row];
        cell.bidClick = ^{
            
            if (![Factory isLogin]) {
                [Factory loadLoginScreen];
            }else{
                BidViewController *vc = [[BidViewController alloc]init];
                vc.hidesBottomBarWhenPushed = YES;
                vc.data = _dataArr[indexPath.row];
                
                [self.navigationController pushViewController:vc animated:YES];
            }
            
        };
        return cell;
    }else{
        InvestNoDataCell *cell = [tableView dequeueReusableCellWithIdentifier:InvestNoDataCellReuseId forIndexPath:indexPath];
        [cell.upgradeBtn addTarget:self action:@selector(upgredeMothod:) forControlEvents:UIControlEventTouchUpInside];
        return cell;
    }
}

- (void)upgredeMothod:(UIButton *)sender
{
    self.tabBarController.tabBar.hidden = YES;
    [_filterController show];
    _tableView.mm_height = kScreenHeight - kNavigationBarHeight - kRankViewHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return self.dataArr.count ? 135.f : kScreenHeight - kNavigationBarHeight - kTabbarHeight - kRankViewHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

- (ZYSideSlipFilterRegionModel *)commonFilterRegionModelWithKeyword:(NSString *)keyword selectionType:(CommonTableViewCellSelectionType)selectionType {
    ZYSideSlipFilterRegionModel *model = [[ZYSideSlipFilterRegionModel alloc] init];
    model.isShowAll = YES;
    model.containerCellClass = @"SideSlipCommonTableViewCell";
    model.regionTitle = keyword;
    model.customDict = @{REGION_SELECTION_TYPE:@(selectionType)};
    model.itemList = @[[self createItemModelWithTitle:@"低风险" itemId:@"0" selected:YES],
                       [self createItemModelWithTitle:@"中风险" itemId:@"1" selected:NO],
                       [self createItemModelWithTitle:@"高风险" itemId:@"2" selected:NO],
                       ];
    return model;
}

- (ZYSideSlipFilterRegionModel *)commonFilterRegionRiswLevelModelWithKeyword:(NSString *)keyword selectionType:(CommonTableViewCellSelectionType)selectionType {
    ZYSideSlipFilterRegionModel *model = [[ZYSideSlipFilterRegionModel alloc] init];
    model.isShowAll = YES;
    model.containerCellClass = @"SideSlipCommonTableViewCell";
    model.regionTitle = keyword;
    model.customDict = @{REGION_SELECTION_TYPE:@(selectionType)};
    model.itemList = @[[self createItemModelWithTitle:@"AA" itemId:@"0" selected:NO],
                       [self createItemModelWithTitle:@"A" itemId:@"1" selected:NO],
                       [self createItemModelWithTitle:@"B" itemId:@"2" selected:NO],
                       [self createItemModelWithTitle:@"C" itemId:@"3" selected:NO],
                       [self createItemModelWithTitle:@"D" itemId:@"4" selected:NO],
                       [self createItemModelWithTitle:@"E" itemId:@"5" selected:NO],
                       [self createItemModelWithTitle:@"F" itemId:@"6" selected:NO],
                       ];
    return model;
}

- (ZYSideSlipFilterRegionModel *)commonFilterRegionTimeLimitModelWithKeyword:(NSString *)keyword selectionType:(CommonTableViewCellSelectionType)selectionType {
    ZYSideSlipFilterRegionModel *model = [[ZYSideSlipFilterRegionModel alloc] init];
    model.isShowAll = YES;
    model.containerCellClass = @"SideSlipCommonTableViewCell";
    model.regionTitle = keyword;
    model.customDict = @{REGION_SELECTION_TYPE:@(selectionType)};
    model.itemList = @[[self createItemModelWithTitle:@"1-3个月" itemId:@"0" selected:NO],
                       [self createItemModelWithTitle:@"3-6个月" itemId:@"1" selected:NO],
                       [self createItemModelWithTitle:@"7-9个月" itemId:@"2" selected:NO],
                       [self createItemModelWithTitle:@"9-12个月" itemId:@"3" selected:NO],
                       [self createItemModelWithTitle:@"12-24个月" itemId:@"4" selected:NO],
                       [self createItemModelWithTitle:@">24个月" itemId:@"5" selected:NO],
                       ];
    return model;
}

- (ZYSideSlipFilterRegionModel *)commonFilterRegionInterestRateModelWithKeyword:(NSString *)keyword selectionType:(CommonTableViewCellSelectionType)selectionType {
    ZYSideSlipFilterRegionModel *model = [[ZYSideSlipFilterRegionModel alloc] init];
    model.isShowAll = YES;
    model.containerCellClass = @"SideSlipPriceTableViewCell";
    model.regionTitle = keyword;
//    model.customDict = @{REGION_SELECTION_TYPE:@(selectionType)};
//    model.itemList = @[[self createItemModelWithTitle:@"12%" itemId:@"0" selected:NO],
//                       [self createItemModelWithTitle:@"14%" itemId:@"1" selected:NO],
//                       [self createItemModelWithTitle:@"15%" itemId:@"2" selected:NO],
//                       [self createItemModelWithTitle:@"16%" itemId:@"3" selected:NO],
//                       [self createItemModelWithTitle:@"17%" itemId:@"4" selected:NO],
//                       ];
    return model;
}

- (CommonItemModel *)createItemModelWithTitle:(NSString *)itemTitle
                                       itemId:(NSString *)itemId
                                     selected:(BOOL)selected {
    CommonItemModel *model = [[CommonItemModel alloc] init];
    model.itemId = itemId;
    model.itemName = itemTitle;
    model.selected = selected;
    return model;
}


- (NSMutableArray *)dataArr{
    if (_dataArr == nil) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

@end
